<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第10章 个人中心和全局搜索功能实现, 湮灭星空,博客,Python,后端">
    <meta name="description" content="个人中心和系统全局功能实现、 全局功能包括全局导航栏功能和全局搜索功能的实现。 个人中心功能包括个人信息的展示和修改、 头像修改、密码修改、邮箱修改。 邮箱修改需要通过邮箱验证才能修改。 用户学习的课程展示、 用户的收藏展示以及删除收藏功能">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>第10章 个人中心和全局搜索功能实现 | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/7.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第10章 个人中心和全局搜索功能实现
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/django/">
                                <span class="chip bg-color">django</span>
                            </a>
                        
                            <a href="/tags/xadmin/">
                                <span class="chip bg-color">xadmin</span>
                            </a>
                        
                            <a href="/tags/python/">
                                <span class="chip bg-color">python</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/imooc/" class="post-category">
                                imooc
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-04-15
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2019-12-06
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    269
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    1 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>个人中心和系统全局功能实现、 全局功能包括全局导航栏功能和全局搜索功能的实现。 个人中心功能包括个人信息的展示和修改、 头像修改、密码修改、邮箱修改。 邮箱修改需要通过邮箱验证才能修改。 用户学习的课程展示、 用户的收藏展示以及删除收藏功能，最后是用户的个人消息展示…</p>
<h2 id="10-1-配置全局导航"><a class="header-anchor" href="#10-1-配置全局导航"></a>10-1 配置全局导航</h2>
<p>关于导航栏当前页面所在分类颜色加深的解决方案：</p>
<ul>
<li>
<p>在视图函数传入<code>section</code>参数，在导航栏的每一分类比对 <code>section</code>的值，显示颜色</p>
<ul>
<li>缺点：在每一个用到导航栏的视图函数都需要传入<code>section</code>参数，太麻烦</li>
</ul>
</li>
<li>
<p>在前端获取当前页面的 <code>url</code>，从 <code>url</code>内获取关于当前页面所属分类的<strong>关键字</strong>，然后使用关键字进行比对，显示颜色</p>
</li>
</ul>
<pre><code class="language-jinja2">&lt;html&gt;
&lt;body&gt;
&lt;li class=&quot;{% if request.path == '/' %}active{% endif %}">
<a href="{% url 'index' %}">首页</a>
</li>
<li class="{% if request.path|slice:'9' == '/courses/' %}active{% endif %}&quot;&gt;
&lt;a href=&quot;{% url 'course_list' %}&quot;&gt;
公开课&lt;img class=&quot;hot&quot; src=&quot;/static/images/nav_hot.png&quot;&gt;
&lt;/a&gt;
&lt;/li&gt;
&lt;li class=&quot;{% if request.path|slice:'9' == '/teacher/' %}active{% endif %}">
<a href="{% url 'teacher_list' %}">授课教师</a>
</li>
<li class="{% if request.path|slice:'5' == '/org/' %}active{% endif %}&quot;&gt;
&lt;a href=&quot;{% url 'org_list' %}&quot;&gt;授课机构&lt;/a&gt;
&lt;/li&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<ul>
<li><code>request.path</code>：获取当前页面的 <code>url</code></li>
<li>使用过滤器 <code>|</code> + <code>slice:'number'</code>功能获取关于页面分类的关键字</li>
</ul>
<h2 id="10-2-全局搜索功能开发"><a class="header-anchor" href="#10-2-全局搜索功能开发"></a>10-2 全局搜索功能开发</h2>
<p>搜索功能的 js 函数：</p>
<p>很容易看出下面对<code>course</code>、<code>teacher</code>、<code>org</code> 三个分类分别作了不同的 <code>request_url</code>，是固定了的，一但 url 发生变化，这里也需要作出更改。</p>
<pre><code class="language-js">//顶部搜索栏搜索方法
function search_click(){
    var type = $('#jsSelectOption').attr('data-value'),
        keywords = $('#search_keywords').val(),
        request_url = '';
    if(keywords == &quot;&quot;){
        return
    }
    if(type == &quot;course&quot;){
        request_url = &quot;/course/?keywords=&quot;+keywords
    }else if(type == &quot;teacher&quot;){
        request_url = &quot;/teacher/?keywords=&quot;+keywords
    }else if(type == &quot;org&quot;){
        request_url = &quot;/org/?keywords=&quot;+keywords
    }
    window.location.href = request_url
}
</code></pre>
<p>bobby 这个搜索功能感觉太差了，在前端分出不同的访问地址？url 结构发生变化就麻烦了还得改 js 文件。所以自己写了一个：</p>
<ol>
<li>
<p>重写 js 函数，直接将搜索类型和搜索的关键字传递给搜索视图类：</p>
<pre><code class="language-javascript">//顶部搜索栏搜索方法
function search_click() {
    var type = $('#jsSelectOption').attr('data-value'),
        keywords = $('#search_keywords').val(),
        request_url = '';
    if (keywords == &quot;&quot;) {
        return
    }
    request_url = '/search?type=' + type + '&amp;keywords=' + keywords;
    window.location.href = request_url
}
</code></pre>
</li>
<li>
<p>新增搜索功能的视图类和 url，在 search 视图类中根据搜索类型，重定向到对应的视图函数（带参数），<strong>搜索 URL 在这里定义</strong>：</p>
<pre><code class="language-python"># urls.py
path('search/', SearchView.as_view(), name='search'),

# views.py
class SearchView(View):
    def get(self, request):
        &quot;&quot;&quot;
        :param type: 是 js 传过来的参数，名字在 js 里面定义的
        :param keywords: 是 js 传过来的参数，名字在 js 里面定义的
        &quot;&quot;&quot;
        type = request.GET.get('type', '')
        keywords = request.GET.get('keywords', '')
        url = ''
        if type == 'course':
            url = '/course/'
        if type == 'teacher':
            url = '/teacher/'
        if type == 'org':
            url = '/org/'
        return HttpResponseRedirect(&quot;{}?type={}&amp;keywords={}&quot;.format(url, type, keywords))
</code></pre>
</li>
<li>
<p>又定义了一个 search 方法，用于在不同视图类中使用搜索功能，<strong>搜索分类下的内容在这里定义</strong>：</p>
<pre><code class="language-python">from django.db.models import Q


def search(request, objects):
    # 全局搜索
    results = objects
    type = request.GET.get('type', '')
    keywords = request.GET.get('keywords', '')

    if type == 'course' and keywords:  # 课程搜索
        results = objects.filter(Q(name__icontains=keywords) | Q(detail__icontains=keywords))

    if type == 'teacher' and keywords:  # 讲师搜索
        results = objects.filter(Q(name__icontains=keywords))

    if type == 'org' and keywords:  # 机构搜索
        results = objects.filter(Q(name__icontains=keywords) | Q(description__icontains=keywords))

    return results
</code></pre>
</li>
<li>
<p>最后在不同类中使用搜索功能：</p>
<pre><code class="language-python"># 课程列表的视图类
class CourseListView(View):
    def get(self, request):
        all_courses = Course.objects.all()
        hot_courses = all_courses.order_by('-click_nums')

        all_courses = search(request, all_courses)
        ...
        
# 讲师列表的视图类
class TeacherList(View):
    def get(self, request):
        teachers = Teacher.objects.all()
        hot_teachers = teachers.order_by('-click_nums')[:5]

        teachers = search(request, teachers)
        ...
        
# 机构列表的视图类
class OrgView(View):
    &quot;&quot;&quot;
    课程结构列表页
    &quot;&quot;&quot;

    def get(self, request):
        all_orgs = CourseOrg.objects.all()
        hot_orgs = all_orgs.order_by('-click_nums')[:3]
        citys = CityDict.objects.all()

        all_orgs = search(request, all_orgs)
        ...
</code></pre>
</li>
</ol>
<p>遗留问题带解决：</p>
<ul>
<li>搜索完之后在搜索栏的搜索关键字就消失了
<ul>
<li>最好保留搜索关键字</li>
</ul>
</li>
<li>没有搜索记录展示
<ul>
<li>最好点击搜索框可以展示搜索历史</li>
</ul>
</li>
<li>其实这种三个分类搜索分别定向到三个不同的 url 页面很鸡肋，最好将搜索功能合并一个试图类中完成并返回</li>
<li>不能对搜索结果做排序，比如：城市、机构类别、人气等等</li>
</ul>
<h2 id="10-3-个人信息展示"><a class="header-anchor" href="#10-3-个人信息展示"></a>10-3 个人信息展示</h2>
<h2 id="10-4-修改密码和修改头像1"><a class="header-anchor" href="#10-4-修改密码和修改头像1"></a>10-4 修改密码和修改头像1</h2>
<h2 id="10-5-修改密码和修改头像2"><a class="header-anchor" href="#10-5-修改密码和修改头像2"></a>10-5 修改密码和修改头像2</h2>
<h3 id="修改用户头像"><a class="header-anchor" href="#修改用户头像"></a>修改用户头像</h3>
<p>显然需要一个视图类专门处理用户头像上传。</p>
<ol>
<li>找到 html 中修改头像的部分发现是一个 <code>form</code>表单提交的用户头像，修改 <code>form</code>的 <code>action</code>属性为上传头像视图类的地址，顺便添加上 <code>{% csrf_token %}</code>，<code>Django</code>中每个表单的提交都需要<code>{% csrf_token %}</code>，这是为了防止跨域攻击。</li>
</ol>
<pre><code class="language-html">   &lt;form class=&quot;clearfix&quot; id=&quot;jsAvatarForm&quot; enctype=&quot;multipart/form-data&quot; autocomplete=&quot;off&quot;
         method=&quot;post&quot; action=&quot;{% url 'image_upload' %}&quot; target='frameFile'&gt;
       &lt;label class=&quot;changearea&quot; for=&quot;avatarUp&quot;&gt;
           &lt;span id=&quot;avatardiv&quot; class=&quot;pic&quot;&gt;
               &lt;img width=&quot;100&quot; height=&quot;100&quot; class=&quot;js-img-show&quot; id=&quot;avatarShow&quot; 
                    src=&quot;{{ MEDIA_URL }}{{ request.user.image }}&quot;/&gt;&lt;/span&gt;
           &lt;span class=&quot;fl upload-inp-box&quot; style=&quot;margin-left:70px;&quot;&gt;
               &lt;span class=&quot;button btn-green btn-w100&quot; id=&quot;jsAvatarBtn&quot;&gt;修改头像&lt;/span&gt;
               &lt;input type=&quot;file&quot; name=&quot;image&quot; id=&quot;avatarUp&quot; class=&quot;js-img-up&quot;/&gt;
           &lt;/span&gt;
       &lt;/label&gt;
       {% raw %}{% csrf_token %}{% endraw %}
   &lt;/form&gt;
</code></pre>
<ol start="2">
<li>
<p>因为是表单提交数据储存到数据库，所以需要先写一个 <code>form</code>做验证，使用 <code>ModelForm</code>在 <code>forms.py</code>中：</p>
<pre><code class="language-python">class ImageUploadForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['image']
</code></pre>
</li>
<li>
<p>在 <a href="http://views.py" target="_blank" rel="noopener">views.py</a> 中创建视图类：</p>
<ul>
<li><code>request</code>在传递文件的时候会将文件储存在 <code>request.FILES</code>中，所有我们需要在实例化 <code>ModelForm</code>的时候传入 <code>request.FILES</code></li>
<li><code>ModelForm</code>会将验证过的字段存放在 <code>cleaned_data</code>中，该对象是一个字典，所以可以用字典的方法取值</li>
</ul>
<pre><code class="language-python">class ImageUploadView(LoginRequiredMixin, View):
    &quot;&quot;&quot;
    用户修改头像
    &quot;&quot;&quot;

    def post(self, request):
        image_upload_form = ImageUploadForm(request.POST, request.FILES)
        if image_upload_form.is_valid():
            image = image_upload_form.cleaned_data.get('image')
            request.user.image = image
            request.user.save()
</code></pre>
</li>
<li>
<p>在 <code>urls.py</code>中创建<code>url</code></p>
<pre><code class="language-python"># 用户头像上传
path('image/upload/', ImageUploadView.as_view(), name='image_upload')
</code></pre>
</li>
</ol>
<p>好了现在就可以进行测试了，发现完美修改用户头像。</p>
<h3 id="更简单的头像修改方法"><a class="header-anchor" href="#更简单的头像修改方法"></a>更简单的头像修改方法</h3>
<p>上面使用了 <code>ModelForm</code>，其实上面的视图类可以更简单，因为 <code>ModelForm</code>理论上是可以直接保存的，我们可以将<code>ModelForm</code>的性能用起来，只需要在实例化<code>ModelForm</code>的时候传入一个实例化的对象，就可以将该<strong>实例对象</strong>与<code>ModelForm</code>绑定起来，表单验证完之后，可以直接对<code>ModelForm</code>的实例对象进行保存。</p>
<pre><code class="language-python">class ImageUploadView(LoginRequiredMixin, View):
    &quot;&quot;&quot;
    用户修改头像
    &quot;&quot;&quot;

    def post(self, request):
        image_upload_form = ImageUploadForm(request.POST, request.FILES, instance=request.user)
        if image_upload_form.is_valid():
            image_upload_form.save()
</code></pre>
<h2 id="10-6-修改邮箱和用户信息1"><a class="header-anchor" href="#10-6-修改邮箱和用户信息1"></a>10-6 修改邮箱和用户信息1</h2>
<h2 id="10-7-修改邮箱和用户信息2"><a class="header-anchor" href="#10-7-修改邮箱和用户信息2"></a>10-7 修改邮箱和用户信息2</h2>
<h2 id="10-8-我的课程"><a class="header-anchor" href="#10-8-我的课程"></a>10-8 我的课程</h2>
<h2 id="10-9-我的收藏功能1"><a class="header-anchor" href="#10-9-我的收藏功能1"></a>10-9 我的收藏功能1</h2>
<h2 id="10-10-我的收藏功能2"><a class="header-anchor" href="#10-10-我的收藏功能2"></a>10-10 我的收藏功能2</h2>
<h2 id="10-11-我的消息"><a class="header-anchor" href="#10-11-我的消息"></a>10-11 我的消息</h2>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2019/04/15/imooc/di-10-zhang-ge-ren-zhong-xin-he-quan-ju-sou-suo-gong-neng-shi-xian/">https://www.klause.cn/2019/04/15/imooc/di-10-zhang-ge-ren-zhong-xin-he-quan-ju-sou-suo-gong-neng-shi-xian/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/django/">
                                    <span class="chip bg-color">django</span>
                                </a>
                            
                                <a href="/tags/xadmin/">
                                    <span class="chip bg-color">xadmin</span>
                                </a>
                            
                                <a href="/tags/python/">
                                    <span class="chip bg-color">python</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/04/15/bu-shu/hexo-github-bu-shu-bo-ke-yu-dao-de-wen-ti/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/10.jpg" class="responsive-img" alt="Hexo + Github 部署博客踩坑">
                        
                        <span class="card-title">Hexo + Github 部署博客踩坑</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            模板渲染错误

Hexo 解析出错：
Template render error: unknown block tag
Template render error: tag name expected


当 markdown中包含
{{ 
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-04-15
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/hexo/">
                        <span class="chip bg-color">hexo</span>
                    </a>
                    
                    <a href="/tags/deploy/">
                        <span class="chip bg-color">deploy</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/04/15/imooc/di-11-zhang-shou-ye-quan-ju-gong-neng-xi-jie-he-404-yi-ji-500-ye-mian-pei-zhi/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/18.jpg" class="responsive-img" alt="第11章 首页、全局功能细节和404以及500页面配置">
                        
                        <span class="card-title">第11章 首页、全局功能细节和404以及500页面配置</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本章主要完善整站的实现细节， 如修改点击数、收藏数以及登出功能等。 接着实现系统的首页， 最后配置系统的全局404和500页面
11-1 登出和点击数以及收藏数完善
11-2 首页功能开发1
11-3 首页功能开发2
11-4 404和50
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-04-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/imooc/" class="post-category">
                                    imooc
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/django/">
                        <span class="chip bg-color">django</span>
                    </a>
                    
                    <a href="/tags/xadmin/">
                        <span class="chip bg-color">xadmin</span>
                    </a>
                    
                    <a href="/tags/python/">
                        <span class="chip bg-color">python</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
